var DBFactory = require('../db/mysql_db');
var orderDao = module.exports;
require('../util/common');
var CONFIG = require('../config');

function getTotalCount(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql;
    var arr =  [];
    if(data.isAdmin) {
        sql = 'select count(*) as count from shop_order LEFT JOIN shop_goods on shop_order.gid = shop_goods.id ' +
            ' LEFT JOIN shop_receive_addr on shop_receive_addr.id = shop_order.add_id ';
    } else {
        sql = 'select count(*) as count from shop_order LEFT JOIN shop_goods on shop_order.gid = shop_goods.id ' +
            ' LEFT JOIN shop_receive_addr on shop_receive_addr.id = shop_order.add_id where shop_order.uid = ? ';
        arr.push(data.uid);
    }
    DBFactory.poolQuery(sql, arr,
        function(){
            cb('no collection');
        },function (err,result) {
            if(err){
                cb(err);
                console.log('getTotalCount Err: ' + err);
                return;
            }
            cb(null, result[0].count);
        }
    );
}

orderDao.list = function(data, cb) {
    if(!data) return cb(new ERR(500));
    getTotalCount(data, function(err, total){
        if(err) {
            cb('获取列表失败！');
        } else {
            var sql;
            var arr =  [];
            if(data.isAdmin) {
                sql = 'select shop_order.*, shop_goods.title, shop_goods.score, ' +
                    ' shop_receive_addr.detail from shop_order LEFT JOIN shop_goods on shop_order.gid = shop_goods.id ' +
                    ' LEFT JOIN shop_receive_addr on shop_receive_addr.id = shop_order.add_id ';
            } else {
                sql = 'select shop_order.*, shop_goods.title, shop_goods.score, ' +
                    ' shop_receive_addr.detail from shop_order LEFT JOIN shop_goods on shop_order.gid = shop_goods.id ' +
                    ' LEFT JOIN shop_receive_addr on shop_receive_addr.id = shop_order.add_id where shop_order.uid = ? ';
                arr.push(data.uid);
            }
            sql += ' order by created_date desc limit ?, ?';
            arr.push(data.start);
            arr.push(data.size);
            console.log(sql);
            DBFactory.poolQuery(sql, arr,
                function(){
                    cb('no collection');
                },function (err,result) {
                    if(err){
                        cb(err);
                        console.log('list Err: ' + err);
                        return;
                    }
                    var list = {};
                    list.total = total;
                    list.data = result;
                    list.msg = '';
                    list.code = 200;
                    cb(null, list);
                }
            );
        }
    });
}

function haveAddress(data, cb) {
    var sql = 'SELECT * , if(is_default = 1, id, 0) as default_id from shop_receive_addr where uid= ? ';
    DBFactory.poolQuery(sql, [ data.uid ],
        function(){
            cb('no collection');
        },function (err,result) {
            if(err){
                cb(err);
                console.log('haveAddress Err: ' + err);
                return;
            }
            if(result.length > 0) {
                var add_id;
                var addr;
                for(var i=0; i<result.length; i++) {
                    if(parseInt(result[i].default_id) != 0) {
                        add_id = result[i].default_id;
                        addr = result[i];
                    }
                }
                if(add_id == undefined) {
                    add_id = result[result.length -1].id;
                    addr = result[result.length -1];
                }
                var address = {};
                address.add_id = add_id;
                address.address = addr;
                cb(null, address);
            } else {
                cb(null, false);
            }
        }
    );
}

function getOrderCode(uid) {
    var now = new Date();
    var code ='' + uid + now.getFullYear() + parseInt(now.getMonth() + 1) + now.getDate() + now.getHours() + now.getMinutes() + Math.floor(Math.random()*10) + Math.floor(Math.random()*10);
    return code + '1315';
}

function delCart(data, cb) {
    var sql = 'delete from shop_cart where id in ( ? ) and uid = ? ';
    DBFactory.poolQuery(sql, [data.ids, data.uid],
        function(){
            cb('no collection');
        },function (err,result) {
            if(err){
                cb(err);
                console.log('delCart Err: ' + err);
                return;
            } else {
                cb(null, result);
            }
        }
    );
}

function confirmOrder(data, cb) {
    var sql = 'select sc.gid, sc.num, sg.title, sg.score,sg.content, ' +
        ' (sc.num * sg.score ) cost_score, sg.pic_url from shop_cart as sc ' +
        ' LEFT JOIN shop_goods as sg on sc.gid = sg.id where sc.id in ( ? ) and sc.uid = ? ';
    DBFactory.poolQuery(sql, [ data.ids, data.uid ],
        function(){
            cb('no collection');
        },function (err, result) {
            if(err){
                cb(err);
                console.log('createOrder Err: ' + err);
                return;
            }
            if(data.type) {
                var order_code = getOrderCode(data.uid);
                var orderList = [];
                var comment = data.comment ? data.comment : null;
                var sum = 0;
                for(var i=0; i<result.length; i++) {
                    var order = [];
                    order.push(order_code);
                    order.push(data.uid);
                    order.push(result[i].gid);
                    order.push(data.add_id);
                    order.push(result[i].cost_score);
                    order.push(result[i].num);
                    order.push(0);
                    order.push(result[i].content);
                    order.push(comment);
                    orderList.push(order);
                    sum += parseInt(result[i].cost_score);
                }
                var sql_insert = ' insert into shop_order(`order_code`,`uid`,`gid`,`add_id`,`cost_score`,`num`,`status`,`content`,`comment`) values ? ';
                DBFactory.poolQuery(sql_insert, [ orderList ],
                    function(){
                        cb('no collection');
                    },function (err, r) {
                        if(err){
                            cb(err);
                            console.log('create order Err: ' + err);
                            return;
                        }
                        if(r.affectedRows > 0) {
                            delCart(data, function(e){
                                if(e) {
                                    cb(e);
                                    console.log('delCart Err:' + e);
                                    return;
                                } else {
                                    // cb(null, 'ok');
                                    var orders = {};
                                    orders.sum = sum;
                                    orders.order_code = order_code;
                                    orders.uid = data.uid;
                                    order.token = data.token;
                                    exchange(orders, cb);
                                }
                            });
                        } else {
                            cb('生成订单失败！');
                        }
                    }
                );
            } else {
                var sum = 0;
                for(var i=0; i<result.length; i++) {
                    sum += parseInt(result[i].cost_score);
                }
                var orderInfo = {};
                orderInfo.address = data.address;
                orderInfo.data = result;
                orderInfo.sum = sum;
                orderInfo.ids = data.ids;
                cb(null, orderInfo);
            }
        }
    );
}

orderDao.confirmOrder = function(data, cb) {
    if(!data) return cb(new ERR(500));
    haveAddress(data, function(err, haveAddress){
        if(err) {
            cb('查询地址时发生错误！');
            return;
        } else {
            if(haveAddress) {
                data.add_id = haveAddress.add_id;
                data.address = haveAddress.address;
                confirmOrder(data, function(err, data){
                    if(err) {
                        cb(err);
                    } else {
                        cb(null, data);
                    }
                });
            } else {
                cb(null, {status: 101});
                return;
            }
        }
    });
}

function getAddress(add_id, cb) {
    var sql = 'select * from shop_receive_addr where id = ? ';
    DBFactory.poolQuery(sql, [ add_id ],
        function(){
            cb('no collection');
        },function (err,result) {
            if(err){
                cb(err);
                console.log('getAddress Err: ' + err);
                return;
            } else {
                if(result.length > 0) {
                    cb(null, result[0]);
                } else {
                    cb('获取地址发生错误！');
                }
            }
        }
    );
}

orderDao.submitOrder = function(data, cb) {
    if(!data) return cb(new ERR(500));
    data.type = '确认订单';
    if(data.add_id) {
        getAddress(data.add_id, function(e, d){
            if(e) {
                cb(e);
            } else {
                data.address = d;
                confirmOrder(data, function(err, data){
                    if(err) {
                        cb(err);
                    } else {
                        cb(null, data);
                    }
                });
            }
        });
    } else {
        haveAddress(data, function(err, haveAddress){
            if(err) {
                cb('查询地址时发生错误！');
                return;
            } else {
                if(haveAddress) {
                    data.add_id = haveAddress.add_id;
                    data.address = haveAddress.address;
                    confirmOrder(data, function(err, data){
                        if(err) {
                            cb(err);
                        } else {
                            cb(null, data);
                        }
                    });
                } else {
                    cb(null, {status: 101});
                    return;
                }
            }
        });
    }
}

function getVersion(cb) {
    var sql = 'select max(version) as v from shop_order ';
    DBFactory.poolQuery(sql, [],
        function(){
            cb('no collection');
        },function (err,result) {
            if(err){
                cb(err);
                console.log('getVersion Err: ' + err);
                return;
            } else {
                result = (result.length > 0 && result[0].v) ? result[0].v : 0;
                cb(null , result);
            }
        }
    );
}

orderDao.getVersion = function(cb) {
    getVersion(function(e, result){
        if(e) {
            cb('获取版本号失败！');
        } else {
            cb(null, result);
        }
    })
}

function updateVersion(order_code, cb) {
    var sql = 'update shop_order set version = version + 1 where order_code =  ? ';
    DBFactory.poolQuery(sql, [order_code],
        function(){
            cb('no collection');
        },function (err,result) {
            if(err){
                cb(err);
                console.log('updateVersion Err: ' + err);
                return;
            } else {
                cb(null , 'success!');
            }
        }
    );
}

function exchange(orders, cb) {
    getVersion(function(e, d){
        if(e) {
            console.log('兑换失败,获取版本号失败！');
            cb('兑换失败');
            return;
        } else {
            orders.v = d;
            orders.app_key = CONFIG.appSid;
            orders.app_time = new Date().getTime();
            orders.app_sign = getAppSign(orders.app_key, CONFIG.appSecret, orders.app_time);
            baseRequest(CONFIG.UserCenterHost, '/payment/shopExchange', orders, function(err, data){
                if(err) {
                    cb(err);
                } else {
                    if(data) {
                        updateVersion(orders.order_code, cb);
                    }
                }
            });
        }
    });
}

orderDao.submitByOrderCode = function(data, cb) {
   if(!data) return cb(new ERR(500));
   var sql = 'select sum(cost_score) as sum from shop_order where uid = ?  and order_code = ? ';
    DBFactory.poolQuery(sql, [data.uid, data.order_code],
        function(){
            cb('no collection');
        },function (err,result) {
            if(err){
                cb(err);
                console.log('getTotalScore Err: ' + err);
                return;
            } else {
                result = result[0].sum ? result[0].sum : false;
                if(result) {
                    var orders = {};
                    orders.sum = result;
                    orders.order_code = data.order_code;
                    orders.uid = data.uid;
                    orders.token = data.token;
                    exchange(orders, cb);
                } else {
                    cb('订单编号有误！');
                }
            }
        }
    );
}